package com.cyf.common.core.thread;

import java.io.Closeable;
import java.io.IOException;
import java.util.List;

/**
 * 高并发测试工具类
 *
 */
public class ConcurrencyTester implements Closeable {

    private final SyncFinisher syncFinisher;

    private final int threadSize;

    public ConcurrencyTester(int threadSize) {
        this.threadSize = threadSize;
        this.syncFinisher = new SyncFinisher(threadSize);
    }

    /**
     * 执行测试
     * @param task
     * @return
     */
    public long test(Runnable task) {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i <= threadSize; i++) {
            syncFinisher.addWorker(task);
        }
        syncFinisher.start(true); // 需要设置为同步，主线程阻塞，等待任务执行完毕
        return System.currentTimeMillis() - startTime;
    }

    public long test(List<Runnable> taskList) {
        long startTime = System.currentTimeMillis();
        for (Runnable task : taskList) {
            syncFinisher.addWorker(task);
        }
        syncFinisher.start(true); // 需要设置为同步，主线程阻塞，等待任务执行完毕
        return System.currentTimeMillis() - startTime;
    }

    public void stop() {
        this.syncFinisher.stop();
    }

    @Override
    public void close() throws IOException {
        stop();
    }
}